package Aaaaaa;

import lombok.SneakyThrows;

public class Thread {
    public static void main(String[] args) {
        // 声明一个打印对象
        Thread printNum = new Thread();

        // 创建两个线程
        new java.lang.Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    printNum.printOdd();
                }
            }
        }).start();

        new java.lang.Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    printNum.printEven();
                }
            }
        }).start();
    }

    private int num = 1;

    /**
     * 打印奇数
     */
    boolean b = false;

    public synchronized void printEven() throws InterruptedException {
        // 判断是否是奇数,如果是的话阻塞
        while (b) {
            this.wait();
        }
        // 如果不是奇数,打印
        for (int i = 0; i < 2; i++) {
            System.out.println(num);
            num += 2;
        }
        b = true;
        // 通知另一个线程
        this.notify();

    }

    /**
     * 打印偶数
     */
    int m = 2;

    public synchronized void printOdd() throws InterruptedException {
        while (!b) {
            this.wait();
        }
        // 打印结果
        System.out.println(m);
        m += 2;
        b = false;
        // 通知其他线程
        this.notify();
    }

}
